package com.by.rpc.netty;

import com.by.rpc.config.KryoSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Kryo编码器，用于将对象编码为字节数组
 */
public class KryoEncoder extends MessageToByteEncoder<Object> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if (msg == null) {
            throw new IllegalArgumentException("Cannot encode null message");
        }

        try {
            // 使用Kryo序列化对象
            byte[] data = KryoSerializer.serialize(msg);

            // 写入数据长度和数据
            out.writeInt(data.length);
            out.writeBytes(data);
        } catch (Exception e) {
            // 记录序列化异常
            System.err.println("Failed to serialize object: " + e.getMessage());
            throw e; // 向上抛出异常，由Netty处理
        }
    }
}